import React, { Fragment } from 'react';
import { Divider, Popconfirm, Dropdown, Menu, Icon, Modal, Tooltip } from 'antd';

/** 分组 */
const groupArr = (list, field) => {
  let group = [];
  list.forEach(i => {
    const f = group.find(j => i[field] === j[field]);
    if (f) f.options.push(i);
    else {
      group.push({
        [field]: i[field],
        options: [i],
      });
    }
  });
  return group;
};
/**
 * 自定义列操作控件
 * @param text 文本
 * @param show 是否展示（默认true）
 * @param permissions 权限值
 * @param disabled 是否有效
 * @param icon 图标
 * @param justIcon 只展示图标
 * @param popconfirm 是否需要确认提示框
 * @param popconfirmContent 确认提示框的类容
 * @param tip 提示信息
 * @param group 是否是分组按钮
 * @param onClick 处理函数
 */
class AxColumnAction extends React.Component {
  render() {
    const permissions = parseInt(localStorage.getItem('ax-auth-permissions'));
    const { buttons } = this.props;
    /** 可展示按钮 */
    const showButtons = buttons.filter(i => i.show === undefined || i.show);
    /** 有权限的按钮 */
    const permissionButtons = showButtons.filter(
      i => !i.permissions || (permissions & i.permissions) > 0,
    );
    if (permissionButtons.length === 0) {
      return '暂无权限';
    }
    /** 普通按钮 */
    const normalButtons = permissionButtons.filter(i => !i.group);
    /** 分组按钮 */
    const groupButtons = permissionButtons.filter(i => i.group);
    /** 将分组按钮，根据名称再次进行分组 */
    const nameGroupButtons = groupArr(groupButtons, 'group');
    const handleMore = (key, items) => {
      const item = items[key];
      if (item.popconfirm === true) {
        Modal.confirm({
          title: '确认操作',
          content: item.popconfirmContent ? item.popconfirmContent : `确认${item.text}吗？`,
          okText: '确认',
          cancelText: '取消',
          onOk: () => item.onClick && item.onClick(),
        });
      } else {
        item.onClick && item.onClick();
      }
    };
    const getMoreBtn = ({ name, items }) => (
      <Dropdown
        trigger={['click']}
        overlay={
          <Menu onClick={({ key }) => handleMore(key, items)}>
            {items.map((i, idx) => (
              <Menu.Item key={idx} disabled={!!(i.disabled && i.disabled === true)}>
                {i.text}
              </Menu.Item>
            ))}
          </Menu>
        }
      >
        {items.length > 0 ? (
          <a className="ant-dropdown-link" onClick={e => e.preventDefault()}>
            {name === true ? '更多操作' : name} <Icon type="down" />
          </a>
        ) : null}
      </Dropdown>
    );
    return (
      <Fragment>
        {normalButtons.map((i, idx) => (
          <span key={idx}>
            {idx !== 0 ? <Divider type="vertical" /> : null}
            {i.popconfirm === true ? (
              <Popconfirm
                title={i.popconfirmContent ? i.popconfirmContent : `确认${i.text}？`}
                onConfirm={i.onClick && i.onClick}
                onCancel={e => e && e.stopPropagation()}
                okText="确认"
                cancelText="取消"
                onClick={e => e && e.stopPropagation()}
              >
                <Tooltip title={i.tip ? i.tip : null}>
                  <a disabled={!!(i.disabled && i.disabled === true)}>
                    {i.justIcon === true ? null : i.text}
                    {i.icon && <Icon type={i.icon} />}
                  </a>
                </Tooltip>
              </Popconfirm>
            ) : (
                <Tooltip title={i.tip ? i.tip : null}>
                  <a disabled={!!(i.disabled && i.disabled === true)} onClick={(e) => { e.stopPropagation(); i.onClick && i.onClick(e); }}>
                    {i.justIcon === true ? null : i.text}
                    {i.icon && <Icon type={i.icon} />}
                  </a>
                </Tooltip>
              )}
          </span>
        ))}
        {nameGroupButtons && nameGroupButtons.length > 0
          ? nameGroupButtons.map((i, idx) => {
            return (
              <span key={'group' + idx}>
                {(normalButtons && normalButtons.length > 0) || idx > 0 ? (
                  <Divider type="vertical" />
                ) : null}
                {getMoreBtn({ name: i.group, items: i.options })}
              </span>
            );
          })
          : null}
      </Fragment>
    );
  }
}

export default AxColumnAction;
